﻿using System.Collections;

using UnityEngine;

public class Enemy : MonoBehaviour {
	// 血量
	public int hp = 1;

	// 分数
	public int point = 100;

	// Spaceship
	Spaceship spaceship;

	IEnumerator Start ( ) {

		// 获取飞船脚本对象
		spaceship = GetComponent<Spaceship> ( );

		// 向y轴的负值方向移动
		Move (transform.up * -1);

		// canShot是false的场合，结束协程
		if (spaceship.canShot == false) {
			yield break;
		}

		while (true) {

			// 获取所有子元素
			for (int i = 0; i < transform.childCount; i++) {

				Transform shotPosition = transform.GetChild (i);

				// 根据ShotPosition的角度，发射子弹
				spaceship.Shot (shotPosition);
			}

			// 等待shotDelay秒(发射间隔)
			yield return new WaitForSeconds (spaceship.shotDelay);
		}
	}

	// 移动机体
	public void Move (Vector2 direction) {
		GetComponent<Rigidbody2D> ( ).velocity = direction * spaceship.speed;
	}

	void OnTriggerEnter2D (Collider2D c) {
		// 获取图层名
		string layerName = LayerMask.LayerToName (c.gameObject.layer);

		// 图层名是Bullet (Player)之外的时候 什么都不执行d
		if (layerName != "Bullet (Player)") return;

		// 取得PlayerBullet的Transform
		Transform playerBulletTransform = c.transform.parent;

		// 取得Bullet组件
		Bullet bullet = playerBulletTransform.GetComponent<Bullet> ( );

		// 减少hp
		hp = hp - bullet.power;

		// 删除子弹
		Destroy (c.gameObject);

		// 如果hp归零
		if (hp <= 0) {
			// 寻找分数组件，并且加分
			FindObjectOfType<Score> ( ).AddPoint (point);

			// 发生爆炸特效
			spaceship.Explosion ( );

			// 销毁自己(敌人)
			Destroy (gameObject);

		} else {
			// 播放受到Damage动画
			spaceship.GetAnimator ( ).SetTrigger ("Damage");

		}
	}
}
